package mrusanov.ui

import battle.{ BattleContainerPanel, BattlePanel }
import javax.swing._
import management.buildings.BuildingsPanel
import management.staff.StaffPanel
import management.{ CalendarPanel, TeamRosterPanel }
import menu.MenuBuilder
import mrusanov.localization.Localization
import java.awt.event.{ ActionEvent, ActionListener }
import mrusanov.battle.Battle
import mrusanov.team.{ SecondTeam, FirstTeam, Club, Team }
import java.util.{ Date, UUID }
import newgame.NewGamePanel
import player.{ PlayerBigPanel, PlayerSmallPanel }
import util.Random
import mrusanov.player._
import mrusanov.nation.{ World, NationsLoader, Nation }
import java.awt.{ GridLayout, Dimension, BorderLayout }
import mrusanov.buildings.Arena
import mrusanov.league.LeagueInfoSystem
import scala.Some
import mrusanov.util.swing.{ HolderPanel, Event, EventConsumer }
import net.miginfocom.swing.MigLayout
import mrusanov.ui.battle.BattleResultPanel
import java.awt.Frame

class MainFrame extends JFrame with EventConsumer[Any] {
	val centralHolderPanel = new HolderPanel[JPanel]
	val downHolderPanel = new HolderPanel[JPanel]
	var world: Option[World] = None
	private var panelBuilder: PanelBuilder = _

	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
	setExtendedState(Frame.MAXIMIZED_BOTH);
	// TODO: uncomment me
	// setUndecorated(true);
	getContentPane.setLayout(new MigLayout("fill"))
	getContentPane.add(centralHolderPanel, "grow, push, wrap")
	getContentPane.add(downHolderPanel, "width 100%")

	refreshPanelBuilder()
	refreshMenuAndQuickPanel(false)

	override def consumeEvent(event: Event[Any]) {
		event.obj match {
			case battleResult: BattleResultPanel => {
				centralHolderPanel.child = battleResult
				refreshMenuAndQuickPanel(battle = false)
			}
			case panel: CentralPanel => centralHolderPanel.child = panel
			case world: World => {
				this.world = Some(world)
				refreshPanelBuilder()
				refreshMenuAndQuickPanel(battle = false)
				consumeEvent(Event(panelBuilder.firstTeam))
			}
			case battlePanel: BattleContainerPanel => {
				refreshMenuAndQuickPanel(battle = true)
				centralHolderPanel.child = battlePanel
			}
			case _ => throw new IllegalArgumentException("Unknown event type:" + event.obj)
		}
	}

	private def refreshPanelBuilder() {
		world match {
			case None => panelBuilder = new PanelBuilder(this, null)
			case Some(w) => panelBuilder = new PanelBuilder(this, w)
		}
	}

	private def refreshMenuAndQuickPanel(battle: Boolean) {
		val menuBuilder = new MenuBuilder(panelBuilder, this)
		val menuAndPanel = world match {
			case None => (menuBuilder.buildMenuForGameNotStarted,
				menuBuilder.buildQuickMenuForGameNotStarted)
			case Some(_) =>
				if (battle) {
					(menuBuilder.buildMenuForBattle,
						menuBuilder.buildQuickMenuForBattle)
				} else {
					(menuBuilder.buildMenuForGameStarted,
						menuBuilder.buildQuickMenuForGameStarted)
				}
		}

		setJMenuBar(menuAndPanel._1)
		downHolderPanel.child = menuAndPanel._2
	}
}
